<template>
  <div>
    <a-select
      :mode="mode"
      v-model="selectedValue"
      @change="handleChange"
      :placeholder="placeholder"
      :allowClear="allowClear"
      :size="size"
      :disabled="disabled"
      :getPopupContainer="getPopupContainer"
    >
      <a-select-option v-for="dict in data" :key="dict.itemCode">
        <slot :name="dict.itemCode" :option="{code: dict.itemCode, desc: getDesc(dict)}">
          {{ getDesc(dict) }}
        </slot>
      </a-select-option>
    </a-select>

  </div>
</template>
<script>
export default {
  created() {
    this.fetch()
  },
  watch: {
    value: function() {
      this.selectedValue = this.value
    },
    filters() {
      this.fetch()
    },
    dicts() {
      this.fetch()
    },
  },
  props: {
    value: { type: [String, Array] },
    filters: { type: [Array], default: () => { return [] } },
    include: { type: [Boolean], default: true },
    dictCode: { type: [String] },
    placeholder: { type: [String] },
    allowClear: { type: [Boolean], default: true },
    mode: { type: [String], default: 'default' },
    size: { type: [String], default: 'default' },
    disabled: { type: [Boolean] },
    i18n: { type: [Boolean], default: true },
    active: { type: [Boolean], default: true },
    getPopupContainer: { type: [Function], default: () => { return document.body} }
  },
  data() {
    return {
      selectedValue: this.value,
      data: [],
      locale: localStorage.locale,
    }
  },
  computed: {
    dicts() {
      return this.$store.state.dicts[this.dictCode] || []
    }
  },
  methods: {
    getDesc(dict) {
      let label = dict.itemName
      if (this.i18n) {
        label = dict.itemNameI18n[this.locale]
      }
      return label
    },
    fetch () {
      let data = this.dicts
      if (!data) {
        this.data = []
        return
      }
      this.data = data.filter(item => {
        if (this.active) {
          if (!item.isActive) {
            return false
          }
        }
        if (this.filters.length == 0) {
          return true
        }
        if (this.filters.includes(item.itemCode)) {
          if (this.include) {
            return true
          }
        } else {
          if (!this.include) {
            return true
          }
        }
        return false
      })
    },
    handleChange(val) {
      // Should provide an event to pass value to Form.
      this.$emit('change', val)
    },
  }
}
</script>
